package fz.vrd.library.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import java.io.File;
import fz.vrd.library.log.LogFactory;


public class IntentUtils {

    /**
     * 调用系统的图片预览
     */
    public static void toReview(Activity activity, String url) {
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        Uri uri = null;
        String type;
        if (Build.VERSION.SDK_INT >= 24) {
            MimeTypeMap map = MimeTypeMap.getSingleton();
            type = map.getMimeTypeFromExtension(MimeTypeMap
                    .getFileExtensionFromUrl(url));
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName() + ".fileprovider", new File(url));
            intent.setDataAndType(uri, type);
        } else {
            uri = Uri.fromFile(new File(url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            type = "image/*";
        }
        intent.setDataAndType(uri, type);
        activity.startActivity(intent);
    }

    /**
     * 调用系统的图片预览
     */
    private static void toPicture(Fragment fragment, Activity activity, int requestCode) {
        Intent intent = new Intent();
        intent.setType("image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }
        if (fragment != null) {
            fragment.startActivityForResult(intent, requestCode);
        } else if (activity != null) {
            activity.startActivityForResult(intent, requestCode);
        } else {
            LogFactory.getInstance().e("Fragment 和 Activity 都为null");
        }
    }

    /**
     * 调用系统有的图库*
     */
    public static void toPicture(Activity activity, int requestCode) {
        toPicture(null, activity, requestCode);
    }

    /**
     * 调用系统有的图库*
     */
    public static void toPicture(Fragment activity, int requestCode) {
        toPicture(activity, null, requestCode);
    }


    /**
     * 图片裁剪
     *
     * @param act
     * @param uri       原始图片路径
     * @param outputUri 裁剪后的图片路径
     * @param outputX
     * @param outputY
     */
    public static void cropImageUri(Activity act, Uri uri, Uri outputUri, int outputX, int outputY,int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        act.startActivityForResult(intent, requestCode);
    }

    /**
     * 打开系统照相机的方法
     */
    public static void openCamera(Activity context, String path, int requestcode) {
        if (FileUtils.existSDCard()) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri imageUri = null;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                imageUri = Uri.fromFile(new File(path));
            } else {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                imageUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileprovider", new File(path));

            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            context.startActivityForResult(intent, requestcode);
        } else {
            Toast.makeText(context,"请确认已经插入SD卡",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 打开项目权限设置页面
     */
    public static void openSystemSetting(Object object,int code) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        if (object instanceof Activity) {
            Uri uri = Uri.fromParts("package", ((Activity) object).getPackageName(), null);
            intent.setData(uri);
            ((Activity) object).startActivityForResult(intent, code);
        } else if (object instanceof Fragment) {
            Uri uri = Uri.fromParts("package", ((Fragment) object).getActivity().getPackageName(), null);
            intent.setData(uri);
            ((Fragment) object).startActivityForResult(intent, code);
        } else if (object instanceof android.app.Fragment) {
            Uri uri = Uri.fromParts("package", ((android.app.Fragment) object).getActivity().getPackageName(), null);
            intent.setData(uri);
            ((android.app.Fragment) object).startActivityForResult(intent, code);
        }
    }

    /**
     * @param tel : 电话必须是纯数字,否则会报错
     */
    public static void callPhone(Activity activity, String tel) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + tel);
        intent.setData(data);
        activity.startActivity(intent);
    }

    // 跳转到联系人界面   打开通讯录
    public static void openBook(FragmentActivity activity,int code) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.PICK");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setType("vnd.android.cursor.dir/phone_v2");
        activity.startActivityForResult(intent, code);
    }

    //获取选择通讯录的数据
    public static String[] getBookInfo(FragmentActivity activity, Uri uri) {
        String phoneNum = "",contactName = "";
        ContentResolver contentResolver = activity.getContentResolver();
        Cursor cursor = null;
        if (uri != null) {
            cursor = contentResolver.query(uri,
                    new String[]{"display_name","data1"}, null, null, null);
        }
        while (cursor.moveToNext()) {
            contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phoneNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }
        cursor.close();
        //  把电话号码中的  -  符号 替换成空格
        if (phoneNum != null) {
            phoneNum = phoneNum.replaceAll("-", " ");
            // 空格去掉  为什么不直接-替换成"" 因为测试的时候发现还是会有空格 只能这么处理
            phoneNum= phoneNum.replaceAll(" ", "");
        }
        return new String[]{phoneNum,contactName};
    }


}
